package com.lyt.springboot.diffHandler;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class ActionMethodContext implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private Map<String, ActionHandler> methodMap = new HashMap<>();

    /**
     * 将Spring容器中所有实现了策略接口的类添加到Map集合中
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        applicationContext.getBeansOfType(ActionHandler.class).values()
                .stream().forEach(actionHandler -> methodMap.put(actionHandler.actionMethod(),actionHandler));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 根据出行类型获取对应的策略方法
     * @param actionMethod
     * @return
     */
    public ActionHandler getActionMethod(String actionMethod){

        return methodMap.getOrDefault(actionMethod,new ByWalkActionHandler());
    }
}

